<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>cookie基本用法</title>
</head>

<body>
    <div id="user"></div>

</body>
<script>
    // js-cookie 插件

    setCookie('username', 'xiao', 60000)
    // setCookie('username', '', 0) // 删除
    // setCookie('username', '5555', 60000) // 更新cookie
    setCookie('username222', '5555', 60000)
    
    setCookie('555555', '5555', 60000)

    document.getElementById('user').innerHTML ='你好' + getCookie('username')

    function setCookie(key, value, ms) {
        /* 设置cookie 
         * key   string    cookie的名字
         * value  string    cookie的值
         * ms     int      过期时间 ms为单位
        */
        let d = new Date();
        d.setTime(d.getTime() + ms)
        let dgmt = d.toGMTString()
        document.cookie = `${key}=${value};expires=${dgmt}`
    }
   
   
    function getCookie(name) {
        /*  获取cookie
         * name string  cookie的名字
        */
        let cname = name + "=";
        // document.cookie 获取当前域名下的所有的cookie
        const cookies = document.cookie.split(';');
        let c = ''
        for (let i = 0; i < cookies.length; i++) {
            c = cookies[i].trim();
            if (c.indexOf(cname) == 0) {
                return c.substring(cname.length, c.length)
            }
        }
        return ''
    }
</script>

</html>